import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        System.out.println(new Solution().findSubsequences(new int[]{4,6,7,7}));
        System.out.println(new Solution().findSubsequences(new int[]{1,2,1,1,1}));
        System.out.println(new Solution().findSubsequences(new int[]{4,4}));
    }
}

//回溯
class Solution {
    public List<List<Integer>> findSubsequences(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        backtracking(nums, 0, new ArrayDeque<>(), ans);
        return ans;
    }

    void backtracking(int[] nums, int i, Deque<Integer> cur, List<List<Integer>> ans) {
        if (i == nums.length) {
            if (cur.size() >= 2) {
                ans.add(new ArrayList<>(cur));
            }
            return;
        }

        if (cur.isEmpty() || nums[i] >= cur.peekLast()) {
            cur.offerLast(nums[i]);
            backtracking(nums, i + 1, cur, ans);
            cur.pollLast();
        }

        if (cur.isEmpty() || cur.peekLast() != nums[i]) {
            backtracking(nums, i + 1, cur, ans);
        }
    }
}

//二值mask迭代
class Solution1 {
    public List<List<Integer>> findSubsequences(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        for (int mask = 0; mask < 1 << nums.length; mask++) {
            Deque<Integer> subset = new ArrayDeque<>();
            boolean flag = true;
            for (int i = 0; i < nums.length; i++) {
                if ((mask >> i & 1) == 1) {
                    if (!subset.isEmpty() && subset.peekLast() > nums[i]) {
                        flag = false;
                        break;
                    }
                    subset.offerLast(nums[i]);
                } else {
                    if (!subset.isEmpty() && subset.peekLast() == nums[i]) {
                        flag = false;
                        break;
                    }
                }
            }
            if (flag && subset.size() >= 2) {
                ans.add(new ArrayList<>(subset));
            }
        }
        return ans;
    }
}